package com.topcent.tioxyc.controller;

import cn.hutool.core.date.*;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.topcent.tioxyc.constants.KeyConstant;
import com.topcent.tioxyc.mapper.*;
import com.topcent.tioxyc.pojo.*;
import com.topcent.tioxyc.pojo.vo.KeHuzsjuVO;
import com.topcent.tioxyc.pojo.vo.SalesCalculationyuFu;
import com.topcent.tioxyc.pojo.vo.WaiXiangJIaohuoVO;
import com.topcent.tioxyc.pojo.vo.XiaoSYing;
import com.topcent.tioxyc.util.ApiClient;
import com.topcent.tioxyc.util.ConnmeUtils;
import com.topcent.tioxyc.util.PurchaseCommunity;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * @author: weidian
 * @date: 2024/8/8 13:53
 * @Description:
 */
@Slf4j
@RestController
public class TestColler {

    @Autowired
    private Yy1KpiMapper yy1KpiMapper;

    private void chuliYuSuan(Header[] headers, Map<String, Map<String, Double>> weikuan) {
        weikuan.forEach((key, innerMap) -> {
            try {
                Map<String, Object> parameterCxv = new HashMap<>();
                parameterCxv.put("app_id", "6690c7633df0f4b90b4ef551");
                parameterCxv.put("entry_id", "669df675b02f2a74e35ca2f9");

                log.info("Processing innerMap: " + innerMap);
                innerMap.forEach((innerKey, value) -> {
                    HashMap<String, String> communti = new HashMap<>();

                    communti.put("_widget_1721628277543", key);
                    communti.put("_widget_1721628277558", innerKey);
                    List<SAPPurchaseOrder> sapPurchaseOrders = PurchaseCommunity.queryBased(parameterCxv, headers, communti, SAPPurchaseOrder.class);
                    log.info("Processing inner key: " + innerKey + ", value: " + value);
                    SAPPurchaseOrder salesOrderKu = sapPurchaseOrders.get(0);
                    if (salesOrderKu == null) {
                        log.error("SalesOrderKu is null for key: " + key);
                        return;
                    }

                    BigDecimal subtract = sapPurchaseOrders.getFirst().get_widget_1724225500094().subtract(BigDecimal.valueOf(sapPurchaseOrders.getFirst().get_widget_1722475785243()));
                    sapPurchaseOrders.getFirst().set_widget_1731911494439(subtract);

                    Map<String, Object> parameterInster = new HashMap<>();
                    parameterInster.put("app_id", "6690c7633df0f4b90b4ef551");
                    parameterInster.put("entry_id", "669df675b02f2a74e35ca2f9");
                    parameterInster.put("is_start_trigger", "true");
                    parameterInster.put("data_id", sapPurchaseOrders.getFirst().get_id());
                    sapPurchaseOrders.getFirst().set_id(null);
                    parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(sapPurchaseOrders.getFirst()));
                    String jsonSale = JSONUtil.toJsonStr(parameterInster);
                    log.info("Modified sales order prepayment: " + jsonSale);
                    ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSale);

                });

            } catch (Exception e) {
                log.error("Error processing key: {}", key, e);
            }
        });


    }

    @GetMapping("/sendData")
    public String sendDataToLocalDocker() {
        List<Fukuandan> fukuandans = new ArrayList<>();
        List<Fukuandan> fukuandansQ = new ArrayList<>();
        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", "66a0c3efcd4dd2a1c8a4a13f");
        parameter.put("entry_id", "669cb70dab60aa3f4a7bb8b2");
        boolean fale = true;
        String zh = "";
        do {
            if (!zh.isEmpty()) {
                parameter.put("data_id", zh);
            }
            parameter.put("limit", 100);
            String jsonSale = JSONUtil.toJsonStr(parameter);
            JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/list", headers, jsonSale);
            String data = jdySale.getStr("data");
            JSONArray objects = JSONUtil.parseArray(data);
            List<Fukuandan> list = JSONUtil.toList(objects, Fukuandan.class);
            if (list.size() == 100) {
                zh = list.getLast().get_id();
            } else {
                fale = false;
            }
            fukuandans.addAll(list);
        } while (fale);

        for (Fukuandan fukuandan : fukuandans) {
            if (fukuandan.getFlowState() == 1) {
                fukuandansQ.add(fukuandan);
            }
        }

        for (Fukuandan fukuandan : fukuandansQ) {
            Map<String, Map<String, Double>> yushou = new HashMap<>();

            for (Fukuandan.Yufu yufu : fukuandan.get_widget_1721546510495()) {
                if (yushou.containsKey(yufu.get_widget_1721546510504())) {
                    Map<String, Double> stringDoubleMap = yushou.get(yufu.get_widget_1721546510504());
                    if (stringDoubleMap.containsKey(yufu.get_widget_1721616942683())) {
                        Double aDouble = yushou.get(yufu.get_widget_1721546510504()).get(yufu.get_widget_1721616942683());
                        stringDoubleMap.put(yufu.get_widget_1721616942683(), yufu.get_widget_1721546510520() + aDouble);
                    } else {
                        stringDoubleMap.put(yufu.get_widget_1721616942683(), yufu.get_widget_1721546510520());
                    }

                } else {
                    Map<String, Double> yushou001 = new HashMap<>();
                    yushou001.put(yufu.get_widget_1721616942683(), yufu.get_widget_1721546510520());
                    yushou.put(yufu.get_widget_1721546510504(), yushou001);
                }
            }
            chuliYuSuan(headers, yushou);
        }


        return "Data received";
    }


    /**
     * 入库凭证刷新未付总金额
     */
    @GetMapping("/fukuan111")
    public void fukuan111() {
        List<InvoiceDocument> fukuandans = new ArrayList<>();
        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", "66a0c3efcd4dd2a1c8a4a13f");
        parameter.put("entry_id", "66a3727ee9d0a8542c969091");

        Map<String, Object> filter = new HashMap<>();
        filter.put("rel", "and");
        Map<String, Object> cond = new HashMap<>();
        /*cond.put("field", "_widget_1721987711273");
        cond.put("type", "text");
        cond.put("method", "eq");
        List<String> values = new ArrayList<>();
        values.add("5105611710");
        cond.put("value", values);*/
        cond.put("field", "_widget_1731638214170");
        cond.put("type", "text");
        cond.put("method", "empty");
        List<Map<String, Object>> conds = new ArrayList<>();
        conds.add(cond);
        filter.put("cond", conds);
        parameter.put("filter", filter);

        boolean fale = true;
        String zh = "";
        do {
            if (!zh.isEmpty()) {
                parameter.put("data_id", zh);
            }
            parameter.put("limit", 100);
            String jsonSale = JSONUtil.toJsonStr(parameter);
            JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/list", headers, jsonSale);
            String data = jdySale.getStr("data");
            JSONArray objects = JSONUtil.parseArray(data);
            List<InvoiceDocument> list = JSONUtil.toList(objects, InvoiceDocument.class);
            if (list.size() == 100) {
                zh = list.getLast().get_id();
            } else {
                fale = false;
            }
            fukuandans.addAll(list);
        } while (fale);

        for (InvoiceDocument invoiceDocument : fukuandans) {
            asdVo asdVo = new asdVo();
            asdVo.set_id(invoiceDocument.get_id());
            asdVo.set_widget_1731638214169(BigDecimal.ZERO);
            asdVo.set_widget_1731638214170(invoiceDocument.get_widget_1727340673731());

            Map<String, Object> parameterInster = new HashMap<>();
            parameterInster.put("app_id", "66a0c3efcd4dd2a1c8a4a13f");
            parameterInster.put("entry_id", "66a3727ee9d0a8542c969091");
            parameterInster.put("is_start_trigger", "true");
            parameterInster.put("data_id", asdVo.get_id());
            asdVo.set_id(null);
            parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(asdVo));
            String jsonSalee = JSONUtil.toJsonStr(parameterInster);
            ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSalee);
            System.out.println("Data received: " + invoiceDocument.get_widget_1721987711273());
        }



    }

    @GetMapping("/fukuan")
    public String fukuan() {
        List<PaymentForm> fukuandans = new ArrayList<>();
        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", "66a0c3efcd4dd2a1c8a4a13f");
        parameter.put("entry_id", "669cb70dab60aa3f4a7bb8b2");

        Map<String, Object> filter = new HashMap<>();
        filter.put("rel", "and");
        Map<String, Object> cond = new HashMap<>();
        cond.put("field", "flowState");
        cond.put("type", "flowstate");
        cond.put("method", "eq");
        List<Integer> values = new ArrayList<>();
        values.add(1);
        cond.put("value", values);
        List<Map<String, Object>> conds = new ArrayList<>();
        conds.add(cond);
        filter.put("cond", conds);
        parameter.put("filter", filter);

        boolean fale = true;
        String zh = "";
        do {
            if (!zh.isEmpty()) {
                parameter.put("data_id", zh);
            }
            parameter.put("limit", 100);
            String jsonSale = JSONUtil.toJsonStr(parameter);
            JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/list", headers, jsonSale);
            String data = jdySale.getStr("data");
            JSONArray objects = JSONUtil.parseArray(data);
            List<PaymentForm> list = JSONUtil.toList(objects, PaymentForm.class);
            if (list.size() == 100) {
                zh = list.getLast().get_id();
            } else {
                fale = false;
            }
            fukuandans.addAll(list);
        } while (fale);

        List<PaymentForm> weikuan = new ArrayList<>();

        for (PaymentForm fukuandan : fukuandans) {
            if (!fukuandan.get_widget_1721548605263().isEmpty()) {
                weikuan.add(fukuandan);
            }
        }
        Map<String, Object> parameterCxv = new HashMap<>();
        parameterCxv.put("app_id", "66a0c3efcd4dd2a1c8a4a13f");
        parameterCxv.put("entry_id", "66a3727ee9d0a8542c969091");
        for (PaymentForm paymentForm : weikuan) {
            for (PaymentForm.OrderFinalPayment orderFinalPayment : paymentForm.get_widget_1721548605263()) {
                if (orderFinalPayment.get_widget_1727334556949() == null || orderFinalPayment.get_widget_1727334556949().isEmpty() ||
                        orderFinalPayment.get_widget_1721548605264() == null || orderFinalPayment.get_widget_1721548605264().isEmpty()
                        || orderFinalPayment.get_widget_1721548605265() == null) {
                    continue; // 跳过当前遍历
                }

                HashMap<String, String> communti = new HashMap<>();
                communti.put("_widget_1727315685608", orderFinalPayment.get_widget_1727334556949());
                communti.put("_widget_1721987711273", orderFinalPayment.get_widget_1721548605264());
                List<InvoiceDocument> invoiceDocuments = PurchaseCommunity.queryBased(parameterCxv, headers, communti, InvoiceDocument.class);
                if (invoiceDocuments == null || invoiceDocuments.isEmpty()) {
                    continue; // 跳过当前遍历
                }
                // 获取尾款占比
                BigDecimal finalPaymentRate = BigDecimal.valueOf(orderFinalPayment.get_widget_1721548605265());

                // 定义变量用于存储分摊金额总和和未付金额总和
                BigDecimal totalAllocationAmount = BigDecimal.ZERO;
                BigDecimal totalUnpaidAmount = BigDecimal.ZERO;
                BigDecimal totalBalanceAmount = BigDecimal.ZERO;
                InvoiceDocument document = invoiceDocuments.getFirst();
                // 把同一个付款单金额合计起来
                List<PaymentForm> weikuand = new ArrayList<>();
                for (PaymentForm form : weikuan) {
                    for (PaymentForm.OrderFinalPayment finalPayment : form.get_widget_1721548605263()) {
                        String widget1727334556949 = finalPayment.get_widget_1727334556949();
                        if (widget1727334556949.equals(orderFinalPayment.get_widget_1727334556949()) &&
                                finalPayment.get_widget_1721548605264().equals(orderFinalPayment.get_widget_1721548605264())) {
                            weikuand.add(form);
                        }
                    }
                }

                Map<String, BigDecimal> jine = new HashMap<>();
                if (weikuand.size() > 1) {
                    for (PaymentForm form : weikuand) {
                        for (PaymentForm.OrderFinalPayment finalPayment : form.get_widget_1721548605263()) {
                            if (finalPayment.get_widget_1727334556949().equals(orderFinalPayment.get_widget_1727334556949()) &&
                                    finalPayment.get_widget_1721548605264().equals(orderFinalPayment.get_widget_1721548605264())) {
                                BigDecimal fkbl = BigDecimal.valueOf(finalPayment.get_widget_1721548605265());
                                for (InvoiceDocument.InvoiceLineItem invoiceLineItem : document.get_widget_1727340673732()) {

                                    BigDecimal allocationAmount = invoiceLineItem.get_widget_1727340673745()
                                            .multiply(fkbl)
                                            .setScale(10, RoundingMode.HALF_UP);
                                    // 获取键值
                                    String key = invoiceLineItem.get_widget_1727340673742();

                                    // 检查并处理累加逻辑
                                    jine.put(key, allocationAmount.add(jine.getOrDefault(key, BigDecimal.ZERO)));

                                }
                            }
                        }
                    }
                }
                for (InvoiceDocument.InvoiceLineItem invoiceLineItem : document.get_widget_1727340673732()) {
                    //把其他采购订单的付款金额拿过来。
                    Map<String, Object> cgdd = new HashMap<>();
                    cgdd.put("app_id", "6690c7633df0f4b90b4ef551");
                    cgdd.put("entry_id", "669df675b02f2a74e35ca2f9");
                    HashMap<String, String> cgdds = new HashMap<>();
                    cgdds.put("_widget_1721628277543", invoiceLineItem.get_widget_1727340673739());
                    cgdds.put("_widget_1721628277558", invoiceLineItem.get_widget_1727340673735());
                    List<SAPPurchaseOrder> sapPurchaseOrders = PurchaseCommunity.queryBased(cgdd, headers, cgdds, SAPPurchaseOrder.class);
                    if (sapPurchaseOrders.isEmpty() || sapPurchaseOrders.getFirst() == null ||
                            sapPurchaseOrders.getFirst().get_widget_1724225500094() == null) {
                        continue;
                    }


                    // 如果采购订单查询结果不为空，取出已付金额
                    BigDecimal paidAmount = sapPurchaseOrders.isEmpty() || sapPurchaseOrders.getFirst() == null ||
                            sapPurchaseOrders.getFirst().get_widget_1722475785243() == null
                            ? BigDecimal.ZERO
                            : BigDecimal.valueOf(sapPurchaseOrders.getFirst().get_widget_1722475785243());

                    // 计算已付金额
                    BigDecimal allocationAmount = invoiceLineItem.get_widget_1727340673745()
                            .multiply(finalPaymentRate)
                            .setScale(10, RoundingMode.HALF_UP);


                    if (weikuand.size() == 1) {
                        invoiceLineItem.set_widget_1731575068806(allocationAmount);
                    } else {
                        jine.forEach((key, value) -> {
                            if (key.equals(invoiceLineItem.get_widget_1727340673742())) {
                                invoiceLineItem.set_widget_1731575068806(allocationAmount.add(value));
                            }
                        });
                    }
                    // 如果原分摊字段有数据，累加现有值；否则直接写入
//                    BigDecimal existingAllocationAmount = invoiceLineItem.get_widget_1731575068806();
//                    if (existingAllocationAmount != null) {
//                        allocationAmount = allocationAmount.add(existingAllocationAmount);
//                    }


                    // 计算未付金额
                    BigDecimal zongshu = invoiceLineItem.get_widget_1727340673745().add(sapPurchaseOrders.getFirst().get_widget_1724225500094());

                    BigDecimal unpaidAmount = zongshu
                            .subtract(allocationAmount)
                            .subtract(paidAmount)
                            .setScale(10, RoundingMode.HALF_UP);

                    invoiceLineItem.set_widget_1731575068807(unpaidAmount);


                    // 计算分摊总金额累加值：已付金额减去未付金额，加上当前行的分摊金额
                    BigDecimal allocationAdjustment = paidAmount
                            .add(allocationAmount);

                    // 累加到分摊金额总和和未付金额总和
                    totalAllocationAmount = totalAllocationAmount.add(allocationAdjustment);
                    totalUnpaidAmount = totalUnpaidAmount.add(unpaidAmount);
                    totalBalanceAmount = totalBalanceAmount.add(invoiceLineItem.get_widget_1727340673745().subtract(allocationAmount));
                }

                // 输出分摊金额总和和未付金额总和到总记录
                BigDecimal existingTotalAllocationAmount = BigDecimal.ZERO;
                BigDecimal existingTotalUnpaidAmount = BigDecimal.ZERO;

                totalAllocationAmount = totalAllocationAmount.add(existingTotalAllocationAmount);
                totalUnpaidAmount = totalUnpaidAmount.add(existingTotalUnpaidAmount);

                invoiceDocuments.getFirst().set_widget_1731638214169(totalAllocationAmount);
                invoiceDocuments.getFirst().set_widget_1731638214170(totalUnpaidAmount);
                invoiceDocuments.getFirst().set_widget_1731915520417(totalBalanceAmount);


                Map<String, Object> parameterInster = new HashMap<>();
                parameterInster.put("app_id", "66a0c3efcd4dd2a1c8a4a13f");
                parameterInster.put("entry_id", "66a3727ee9d0a8542c969091");
                parameterInster.put("is_start_trigger", "true");
                parameterInster.put("data_id", invoiceDocuments.getFirst().get_id());
                invoiceDocuments.getFirst().set_id(null);
                parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(invoiceDocuments.getFirst()));
                String jsonSalee = JSONUtil.toJsonStr(parameterInster);
                ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSalee);
            }
        }


        return "suu===" + weikuan.size();
    }

    @GetMapping("xinbao")
    public String xinbao() {
        Header[] headers = ConnmeUtils.createHeaders();
        Header[] headers1 = new Header[3];
        String auth = KeyConstant.sapName + ":" + KeyConstant.sapPass;
        String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes());
        String authHeader = "Basic " + encodedAuth;
        headers1[0] = new BasicHeader("Accept", "application/json");
        headers1[1] = new BasicHeader("Authorization", authHeader);
        headers1[2] = new BasicHeader("x-csrf-token", "Fetch");
        JSONObject entries1 =
                ApiClient.sendGetRequest("https://my200654-api.s4hana.sapcloud.cn/sap/opu/odata/sap/API_OUTBOUND_DELIVERY_SRV;v=0002/A_OutbDeliveryHeader", headers1, null);
        String d1 = entries1.getStr("d");
        JSONObject objects1 = JSONUtil.parseObj(d1);
        String results1 = objects1.getStr("results");
        JSONArray objectss1 = JSONUtil.parseArray(results1);
        List<WaiXiangJIaohuoVO> waiXiangJIaohuoVOList = JSONUtil.toList(objectss1, WaiXiangJIaohuoVO.class);

        Iterator<WaiXiangJIaohuoVO> iterator = waiXiangJIaohuoVOList.iterator();
        DateTime now = DateTime.now(); // 获取当前时间，只调用一次提高效率

        while (iterator.hasNext()) {
            WaiXiangJIaohuoVO waiXiangJIaohuoVO = iterator.next();

            // 检查字段是否不为空
            if (waiXiangJIaohuoVO.getYY1_YY1_lachangedateti_DLH() != null
                    && !waiXiangJIaohuoVO.getYY1_YY1_lachangedateti_DLH().isBlank()) {

                // 提取并转换时间戳
                long lct = Long.parseLong(ConnmeUtils.extractTimestamp(waiXiangJIaohuoVO.getYY1_YY1_lachangedateti_DLH()));
                LocalDateTime dateTime2 = ConnmeUtils.convertTimestampToLocalDateTime(lct);
                String formattedDateTime2 = ConnmeUtils.formatDateTime(dateTime2);
                DateTime dateTime4 = new DateTime(formattedDateTime2, DatePattern.NORM_DATETIME_FORMAT);

                // 设置解析后的时间对象回到 VO
                waiXiangJIaohuoVO.setYY1_YY1_lachangedateti_DLHs(dateTime4);

                // 判断日期是否是今天
                if (!DateUtil.isSameDay(dateTime4, now) || !"true".equals(waiXiangJIaohuoVO.getYY1_IF_Release_WMS_DLH())) {
                    iterator.remove();
                } else {
                    Map<String, Object> cgdd = new HashMap<>();
                    cgdd.put("app_id", "668f82dc2f5940fc022143d3");
                    cgdd.put("entry_id", "6729764c7cbf3fba319a16a3");
                    HashMap<String, String> communti = new HashMap<>();
                    communti.put("_widget_1730770509313", waiXiangJIaohuoVO.getDeliveryDocument());
                    List<WaiXiangJIaohuoVO> waiXiangJIaohuoVOS = PurchaseCommunity.queryBased(cgdd, headers, communti, WaiXiangJIaohuoVO.class);
                    if (waiXiangJIaohuoVOS.isEmpty()) {
                        continue;
                    }
                    String widget1730770509314 = waiXiangJIaohuoVOS.getFirst().get_widget_1730770509314();

                    Map<String, Object> kehu = new HashMap<>();
                    kehu.put("app_id", "66a6f42ff97af74b02d217df");
                    kehu.put("entry_id", "66a6f443333584e2c128154f");
                    HashMap<String, String> kehuc = new HashMap<>();
                    communti.put("_widget_1722217596682", widget1730770509314);
                    List<Customer> customers = PurchaseCommunity.queryBased(kehu, headers, kehuc, Customer.class);
                    if (customers.isEmpty()) {
                        continue;
                    }
                    String widget1732245038716 = customers.getFirst().get_widget_1732245038716();
                    if (!widget1732245038716.equals("是")) {
                        continue;
                    }

                    Map<String, Object> waixiang = new HashMap<>();
                    waixiang.put("app_id", "668f82dc2f5940fc022143d3");
                    waixiang.put("entry_id", "6752b495ab2359bc29a39a50");
                    HashMap<String, String> jiaohuo = new HashMap<>();
                    communti.put("_widget_1733473428479", waiXiangJIaohuoVO.getDeliveryDocument());
                    List<DeliveryInfo> deliveryInfos = PurchaseCommunity.queryBased(waixiang, headers, jiaohuo, DeliveryInfo.class);
                    if (deliveryInfos.isEmpty()) {
                        DeliveryInfo deliveryInfo = new DeliveryInfo();
                        deliveryInfo.set_widget_1733473428480(widget1730770509314);
                        deliveryInfo.set_widget_1733473428479(waiXiangJIaohuoVO.getDeliveryDocument());
                        deliveryInfo.set_widget_1740636897665(waiXiangJIaohuoVOS.getFirst().get_widget_1732764831222().get("username"));
                        deliveryInfo.set_widget_1733473796643(waiXiangJIaohuoVO.getSalesOrganization());

                        Map<String, Object> parameterInster = new HashMap<>();
                        parameterInster.put("app_id", "668f82dc2f5940fc022143d3");
                        parameterInster.put("entry_id", "6752b495ab2359bc29a39a50");
                        parameterInster.put("is_start_trigger", "true");
                        parameterInster.put("data_id", deliveryInfo.get_id());
                        deliveryInfo.set_id(null);
                        parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(deliveryInfo));
                        String jsonSale = JSONUtil.toJsonStr(parameterInster);
                        log.info("外向交货单_是否允许交货--{}", jsonSale);
                        ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSale);
                    }

                }


            } else {
                iterator.remove(); // 如果字段为空或 null，也移除
            }
        }


        log.info(String.valueOf(waiXiangJIaohuoVOList.size()));
        return "suu===" + waiXiangJIaohuoVOList.size();
    }

    @GetMapping("kehuzhusju")
    public String kehuzhusju() {
        List<Customer> fukuandans = new ArrayList<>();
        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", "66a6f42ff97af74b02d217df");
        parameter.put("entry_id", "66a6f443333584e2c128154f");
        boolean fale = true;
        String zh = "";
        do {
            if (!zh.isEmpty()) {
                parameter.put("data_id", zh);
            }
            parameter.put("limit", 100);
            String jsonSale = JSONUtil.toJsonStr(parameter);
            JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/list", headers, jsonSale);
            String data = jdySale.getStr("data");
            JSONArray objects = JSONUtil.parseArray(data);
            List<Customer> list = JSONUtil.toList(objects, Customer.class);
            if (list.size() == 100) {
                zh = list.getLast().get_id();
            } else {
                fale = false;
            }
            fukuandans.addAll(list);
        } while (fale);

        Header[] headers1 = new Header[3];
        String auth = KeyConstant.sapName + ":" + KeyConstant.sapPass;
        String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes());
        String authHeader = "Basic " + encodedAuth;
        headers1[0] = new BasicHeader("Accept", "application/json");
        headers1[1] = new BasicHeader("Authorization", authHeader);
        headers1[2] = new BasicHeader("x-csrf-token", "Fetch");
        JSONObject entries1 =
                ApiClient.sendGetRequest("https://my200654-api.s4hana.sapcloud.cn/sap/opu/odata/sap/YY1_CUSTOMER_WMS_CDS/YY1_customer_wms", headers1, null);
        String d1 = entries1.getStr("d");
        JSONObject objects1 = JSONUtil.parseObj(d1);
        String results1 = objects1.getStr("results");
        JSONArray objectss1 = JSONUtil.parseArray(results1);
        List<KeHuzsjuVO> waiXiangJIaohuoVOList = JSONUtil.toList(objectss1, KeHuzsjuVO.class);

        int i = 0;
        for (Customer fukuandan : fukuandans) {
            if (fukuandan.get_widget_1728356780097().isEmpty()) {
                for (KeHuzsjuVO keHuzsjuVO : waiXiangJIaohuoVOList) {
                    if (keHuzsjuVO.getCustomer().equals(fukuandan.get_widget_1722305048887())) {
                        long lct = Long.parseLong(ConnmeUtils.extractTimestamp(keHuzsjuVO.getCreationDate()));
                        LocalDateTime dateTime2 = ConnmeUtils.convertTimestampToLocalDateTime(lct);
                        String formattedDateTime2 = ConnmeUtils.formatDateTime(dateTime2);
                        DateTime dateTime4 = new DateTime(formattedDateTime2, DatePattern.NORM_DATETIME_FORMAT);
                        fukuandan.set_widget_1733204191654(dateTime4);
                        break;
                    }
                }
            } else {
                String date = yy1KpiMapper.setJIan(fukuandan.get_widget_1728356780097());
                if (date == null || date.isEmpty()) { // 先检查是否为 null，再检查是否为空
                    log.info("日期为空{}", fukuandan.get_widget_1722305048887());
                    for (KeHuzsjuVO keHuzsjuVO : waiXiangJIaohuoVOList) {
                        if (keHuzsjuVO.getCustomer().equals(fukuandan.get_widget_1722305048887())) {
                            long lct = Long.parseLong(ConnmeUtils.extractTimestamp(keHuzsjuVO.getCreationDate()));
                            LocalDateTime dateTime2 = ConnmeUtils.convertTimestampToLocalDateTime(lct);
                            String formattedDateTime2 = ConnmeUtils.formatDateTime(dateTime2);
                            DateTime dateTime4 = new DateTime(formattedDateTime2, DatePattern.NORM_DATETIME_FORMAT);
                            fukuandan.set_widget_1733204191654(dateTime4);
                            break;
                        }
                    }
                } else {
                    DateTime parsed = DateUtil.parse(date, "yyyy-MM-dd");
                    fukuandan.set_widget_1733204191654(parsed);
                }
            }
            if (fukuandan.get_widget_1733204191654() != null) {
                Map<String, Object> parameterInster = new HashMap<>();
                parameterInster.put("app_id", "66a6f42ff97af74b02d217df");
                parameterInster.put("entry_id", "66a6f443333584e2c128154f");
                parameterInster.put("is_start_trigger", "true");
                parameterInster.put("data_id", fukuandan.get_id());
                fukuandan.set_id(null);
                parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(fukuandan));
                String jsonSale = JSONUtil.toJsonStr(parameterInster);
                log.info("客户主数据建档日期--{}", jsonSale);
                JSONObject entries = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSale);
                i++;
            }


        }


        return "sssdet:" + i;
    }


    @GetMapping("/shoukuan")
    public String shoukuan() {
        List<SalesCalculation> fukuandans = new ArrayList<>();
        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", "669cb709a73cc1289c49800e");
        parameter.put("entry_id", "669cb70dab60aa3f4a7bb8b2");

        Map<String, Object> filter = new HashMap<>();
        filter.put("rel", "and");
        Map<String, Object> cond = new HashMap<>();
        cond.put("field", "flowState");
        cond.put("type", "flowstate");
        cond.put("method", "eq");
        List<Integer> values = new ArrayList<>();
        values.add(1);
        cond.put("value", values);
        List<Map<String, Object>> conds = new ArrayList<>();
        conds.add(cond);
        filter.put("cond", conds);
        parameter.put("filter", filter);

        boolean fale = true;
        String zh = "";
        do {
            if (!zh.isEmpty()) {
                parameter.put("data_id", zh);
            }
            parameter.put("limit", 100);
            String jsonSale = JSONUtil.toJsonStr(parameter);
            JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/list", headers, jsonSale);
            String data = jdySale.getStr("data");
            JSONArray objects = JSONUtil.parseArray(data);
            List<SalesCalculation> list = JSONUtil.toList(objects, SalesCalculation.class);
            if (list.size() == 100) {
                zh = list.getLast().get_id();
            } else {
                fale = false;
            }
            fukuandans.addAll(list);
        } while (fale);

        List<SalesCalculation> weiyu = new ArrayList<>();

        Map<String, Map<String, SalesCalculationyuFu>> yuFuMap = new HashMap<>();

        for (SalesCalculation fukuandan : fukuandans) {
            if (!fukuandan.get_widget_1721548605263().isEmpty() || !fukuandan.get_widget_1721546510495().isEmpty()) {
                weiyu.add(fukuandan);
                if (!fukuandan.get_widget_1721546510495().isEmpty()) {   //预付款
                    for (SalesCalculation.OrderPrepayment orderPrepayment : fukuandan.get_widget_1721546510495()) {
                        if (yuFuMap.containsKey(orderPrepayment.get_widget_1721546510504())) {
                            if (yuFuMap.get(orderPrepayment.get_widget_1721546510504()).containsKey(orderPrepayment.get_widget_1721616942683())) {
                                SalesCalculationyuFu salesCalculationyuFu = yuFuMap.get(orderPrepayment.get_widget_1721546510504()).get(orderPrepayment.get_widget_1721616942683());
                                salesCalculationyuFu.set_widget_1721546510520(salesCalculationyuFu.get_widget_1721546510520() + orderPrepayment.get_widget_1721546510520());
                                yuFuMap.get(orderPrepayment.get_widget_1721546510504()).put(orderPrepayment.get_widget_1721616942683(), salesCalculationyuFu);
                            } else {
                                SalesCalculationyuFu salesCalculationyuFu = new SalesCalculationyuFu();
                                salesCalculationyuFu.set_widget_1721546510520(orderPrepayment.get_widget_1721546510520());
                                yuFuMap.get(orderPrepayment.get_widget_1721546510504()).put(orderPrepayment.get_widget_1721616942683(), salesCalculationyuFu);
                            }
                        } else {
                            Map<String, SalesCalculationyuFu> wf = new HashMap<>();
                            SalesCalculationyuFu salesCalculationyuFu = new SalesCalculationyuFu();
                            salesCalculationyuFu.set_widget_1721546510520(orderPrepayment.get_widget_1721546510520());
                            wf.put(orderPrepayment.get_widget_1721616942683(), salesCalculationyuFu);
                            yuFuMap.put(orderPrepayment.get_widget_1721546510504(), wf);
                        }
                    }
                }

                if (!fukuandan.get_widget_1721548605263().isEmpty()) {  //尾款
                    for (SalesCalculation.OrderFinalPayment orderFinalPayment : fukuandan.get_widget_1721548605263()) {
                        if (yuFuMap.containsKey(orderFinalPayment.get_widget_1721548605264())) {
                            if (yuFuMap.get(orderFinalPayment.get_widget_1721548605264()).containsKey(orderFinalPayment.get_widget_1721616942684())) {
                                SalesCalculationyuFu salesCalculationyuFu = yuFuMap.get(orderFinalPayment.get_widget_1721548605264()).get(orderFinalPayment.get_widget_1721616942684());
                                salesCalculationyuFu.set_widget_1721548605266(salesCalculationyuFu.get_widget_1721548605266() + orderFinalPayment.get_widget_1721548605266());
                                yuFuMap.get(orderFinalPayment.get_widget_1721548605264()).put(orderFinalPayment.get_widget_1721616942684(), salesCalculationyuFu);
                            } else {
                                SalesCalculationyuFu salesCalculationyuFu = new SalesCalculationyuFu();
                                salesCalculationyuFu.set_widget_1721548605266(orderFinalPayment.get_widget_1721548605266());
                                yuFuMap.get(orderFinalPayment.get_widget_1721548605264()).put(orderFinalPayment.get_widget_1721616942684(), salesCalculationyuFu);
                            }
                        } else {
                            Map<String, SalesCalculationyuFu> wf = new HashMap<>();
                            SalesCalculationyuFu salesCalculationyuFu = new SalesCalculationyuFu();
                            salesCalculationyuFu.set_widget_1721548605266(orderFinalPayment.get_widget_1721548605266());
                            wf.put(orderFinalPayment.get_widget_1721616942684(), salesCalculationyuFu);
                            yuFuMap.put(orderFinalPayment.get_widget_1721548605264(), wf);
                        }
                    }
                }
            }
        }

        yuFuMap.forEach((key, value) -> {
            if(key.equals("2000002840")) {
                System.out.println(5555);
            }
            Map<String, Object> parameterCxv = new HashMap<>();
            parameterCxv.put("app_id", "667230ad22a8581756b77d52");
            parameterCxv.put("entry_id", "669e17aa09cd4f4e279d4d5d");
            HashMap<String, String> communti = new HashMap<>();
            communti.put("_widget_1718759603973", key);
            List<SalesOrderKu> salesOrderKus = PurchaseCommunity.queryBased(parameterCxv, headers, communti, SalesOrderKu.class);
            if (salesOrderKus != null && !salesOrderKus.isEmpty()) {
                double[] zong = {0}; // 使用数组存储值
                value.forEach((key1, value1) -> {
                    for (SalesOrderKu.OrderDetail orderDetail : salesOrderKus.getFirst().get_widget_1718759603981()) {
                        if (orderDetail.get_widget_1718759603995().equals(key1)) {
                            orderDetail.set_widget_1721982279364(value1.get_widget_1721546510520());
                            orderDetail.set_widget_1721982279365(value1.get_widget_1721548605266());
                            orderDetail.set_widget_1722241817628(value1.get_widget_1721546510520() + value1.get_widget_1721548605266());
                            zong[0] += value1.get_widget_1721546510520() + value1.get_widget_1721548605266();
                        }
                    }

                });
                double i = salesOrderKus.getFirst().get_widget_1718759603984() - zong[0];
                if (i<=2) {
                    // 修改出库凭证
                    salesOrderKus.getFirst().set_widget_1734504746939("是");
                    Map<String, Object> parametereefs = new HashMap<>();
                    parametereefs.put("app_id", "669cb709a73cc1289c49800e");
                    parametereefs.put("entry_id", "674d839475ae49b66713aadb");
                    HashMap<String, String> communtid = new HashMap<>();
                    communtid.put("_widget_1731918876993", key);
                    List<DeliveryVoucher> deliveryVouchers = PurchaseCommunity.queryBased(parametereefs, headers, communtid, DeliveryVoucher.class);
                    if (deliveryVouchers != null && !deliveryVouchers.isEmpty()) {
                        for (DeliveryVoucher deliveryVoucher : deliveryVouchers) {
                            deliveryVoucher.set_widget_1734429312703("是");
                            Map<String, Object> parameterInster = new HashMap<>();
                            parameterInster.put("app_id", "669cb709a73cc1289c49800e");
                            parameterInster.put("entry_id", "674d839475ae49b66713aadb");
                            parameterInster.put("is_start_trigger", "true");
                            parameterInster.put("data_id", deliveryVoucher.get_id());
                            deliveryVoucher.set_id(null);
                            parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(deliveryVoucher));
                            String jsonSalee = JSONUtil.toJsonStr(parameterInster);
                            log.info("出库凭证更新是否收款{}", jsonSalee);
                            ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSalee);
                        }
                    }
                    // 修改销售订单引用表的是否收款
                    Map<String, Object> parametereefsyy = new HashMap<>();
                    parametereefsyy.put("app_id", "667230ad22a8581756b77d52");
                    parametereefsyy.put("entry_id", "66a30b55ecb3bf2d5748208c");
                    HashMap<String, String> communtidyy = new HashMap<>();
                    communtidyy.put("_widget_1718759603973", key);
                    List<XiaoSYing> xiaoSYings = PurchaseCommunity.queryBased(parametereefsyy, headers, communtidyy, XiaoSYing.class);
                    if (xiaoSYings != null && !xiaoSYings.isEmpty()) {
                        for (XiaoSYing xiaoSYing : xiaoSYings) {
                            xiaoSYing.set_widget_1734673959092("是");
                            Map<String, Object> parameterInster = new HashMap<>();
                            parameterInster.put("app_id", "667230ad22a8581756b77d52");
                            parameterInster.put("entry_id", "66a30b55ecb3bf2d5748208c");
                            parameterInster.put("is_start_trigger", "true");
                            parameterInster.put("data_id", xiaoSYing.get_id());
                            xiaoSYing.set_id(null);
                            parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(xiaoSYing));
                            String jsonSalee = JSONUtil.toJsonStr(parameterInster);
                            ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSalee);
                        }
                    }


                    Map<String, Object> parameterInster = new HashMap<>();
                    parameterInster.put("app_id", "667230ad22a8581756b77d52");
                    parameterInster.put("entry_id", "669e17aa09cd4f4e279d4d5d");
                    parameterInster.put("is_start_trigger", "true");
                    parameterInster.put("data_id", salesOrderKus.getFirst().get_id());
                    salesOrderKus.getFirst().set_id(null);
                    salesOrderKus.getFirst().set_widget_1718759603978(null);
                    salesOrderKus.getFirst().set_widget_1718759603990(null);

                    for (SalesOrderKu.OrderDetail orderDetail : salesOrderKus.getFirst().get_widget_1718759603981()) {
                        Optional.ofNullable(orderDetail.get_widget_1726803260151())
                                .ifPresent(valuey -> orderDetail.set_widget_1726803260151(valuey.toString()));

                    }
                    SalesOrderKu salesOrderKu = ConnmeUtils.updateFields(salesOrderKus.getFirst());

                    parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(salesOrderKu));
                    String jsonSale = JSONUtil.toJsonStr(parameterInster);
                    ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSale);

                }
            }
        });
        return "suu===" + fukuandans.size() + "预付尾款不为空的：" + weiyu.size();
    }

    @Autowired
    private CustomerInfoMapper customerInfoMapper;
    @Autowired
    private SalesDataMapper salesDataMapper;

    @GetMapping("xiaosouenxi")
    public String xiaosouenxi() {

        List<SalesData> salesData23=new ArrayList<>();
        List<SalesData> salesData24=new ArrayList<>();
        List<SalesData> salesData25=new ArrayList<>();

        String date1="2022-07-01";
        String date2="2023-07-01";
        String date3="2024-07-01";
        String date4="2025-07-01";
        List<CustomerInfo> byxie1 = customerInfoMapper.byxie(date1, date2);
        log.info("即将执行22年的数据");
        int size22 = byxie1.size();
        int i22 = 0;
        BigDecimal totalSalesAmount = byxie1.stream()
                .map(CustomerInfo::getFY23_24SalesAmount) // 提取 FY23_24SalesAmount 字段
                .filter(Objects::nonNull) // 过滤掉 null 值，避免空指针异常
                .reduce(BigDecimal.ZERO, BigDecimal::add); // 累加计算总和
        for (CustomerInfo customerInfo : byxie1) {
            List<Customer> customers = getCustomers(customerInfo);
            List<CustomerInfo> bycode = customerInfoMapper.bycode(date1,date2,customerInfo.getCustomerCode());
            for (CustomerInfo info : bycode) {
                SalesData data=new SalesData();
                data.setSaleNumber(info.getCode());
                data.setCustomerName(customerInfo.getCustomerName());
                data.setTCode(customerInfo.getCustomerCode());
                data.setSalesDepartment(customerInfo.getFollowUpDepartment());
                data.setBusinessStaff(info.getFollowUpPerson());
                data.setCustomerAttribute(customerInfo.getCustomerAttribute());
                data.setCustomerSource(customerInfo.getCustomerSource());
                // 使用 Optional 避免空值判断
                String region = Optional.ofNullable(customers)
                        .filter(list -> !list.isEmpty())
                        .map(List::getFirst)
                        .map(Customer::get_widget_1722233514707)
                        .orElse(null);
                data.setRegion(region);
                Date widget1733204191654 = customers.getFirst().get_widget_1733204191654();
                Date parsed = DateUtil.parse(date2);
                Date parsed1 = DateUtil.parse(date3);
                long betweenMonths1 = DateUtil.betweenMonth(widget1733204191654, parsed, false);
                long betweenMonths2 = DateUtil.betweenMonth(widget1733204191654, parsed1, false);
                long betweenMonths3 = DateUtil.betweenMonth(widget1733204191654, DateUtil.date(), false);
                data.setFY22_23Growth((int) betweenMonths1);
                data.setFY23_24Growth((int) betweenMonths2);
                data.setFY24_25Growth((int) betweenMonths3);
                data.setFY22_23Grade(ConnmeUtils.getCustomerLevel(customerInfo.getFY23_24SalesAmount()));
                data.setFY22_23Status(data.getFY22_23Growth()>12?"老客户":"新客户");
                data.setFY23_24Status(data.getFY23_24Growth()>12?"老客户":"新客户");
                data.setFY24_25Status(data.getFY24_25Growth()>12?"老客户":"新客户");

                data.setFY22_23Jine(customerInfo.getFY23_24SalesAmount());
                BigDecimal percentage = customerInfo.getFY23_24SalesAmount()
                        .divide(totalSalesAmount, 10, RoundingMode.HALF_UP)
                        .multiply(BigDecimal.valueOf(100));
                data.setFYComparison(percentage);
                data.setDalei(info.getDalei());
                data.setInventoryCode(info.getBianma());
                data.setInventoryName(info.getMingcheng());
                data.setUnit(extractLetters(info.getKuanshi()));
                data.setQuantity(info.getShuliang());
                data.setAmount(info.getFY23_24SalesAmount());
                data.setFinanceYear("FY22-23");
                salesData23.add(data);

            }
            i22++;
            log.info("22年的数据---{}/{}",size22,i22);
        }

        List<CustomerInfo> byxie2 = customerInfoMapper.byxie(date2, date3);
        log.info("即将执行23年的数据");
        int size23 = byxie2.size();
        int i23 = 0;
        BigDecimal totalSalesAmount1 = byxie2.stream()
                .map(CustomerInfo::getFY23_24SalesAmount) // 提取 FY23_24SalesAmount 字段
                .filter(Objects::nonNull) // 过滤掉 null 值，避免空指针异常
                .reduce(BigDecimal.ZERO, BigDecimal::add); // 累加计算总和
        for (CustomerInfo customerInfo : byxie2) {
            BigDecimal percentage = customerInfo.getFY23_24SalesAmount()
                    .divide(totalSalesAmount1, 10, RoundingMode.HALF_UP)
                    .multiply(BigDecimal.valueOf(100));
            List<Customer> customers = getCustomers(customerInfo);

            AtomicReference<SalesData> firstMatchedData = new AtomicReference<>();
            salesData23.stream()
                    .filter(data -> customerInfo.getCustomerCode().equals(data.getTCode()))
                    .peek(data -> {
                        // 只存储第一个匹配的数据到 AtomicReference
                        firstMatchedData.compareAndSet(null, data);
                    })
                    .forEach(data -> {
                        // 修改所有匹配的数据
                        data.setFY23_24Grade(ConnmeUtils.getCustomerLevel(customerInfo.getFY23_24SalesAmount()));
                        data.setFY23_24Jine(customerInfo.getFY23_24SalesAmount());
                        data.setFY23Comparison(percentage);
                    });
            SalesData result = firstMatchedData.get();
            List<CustomerInfo> bycode = customerInfoMapper.bycode(date1,date2,customerInfo.getCustomerCode());
            for (CustomerInfo info : bycode) {
                SalesData data=new SalesData();
                data.setSaleNumber(info.getCode());
                data.setCustomerName(customerInfo.getCustomerName());
                data.setTCode(customerInfo.getCustomerCode());
                data.setSalesDepartment(customerInfo.getFollowUpDepartment());
                data.setBusinessStaff(info.getFollowUpPerson());
                data.setCustomerAttribute(customerInfo.getCustomerAttribute());
                data.setCustomerSource(customerInfo.getCustomerSource());
                // 使用 Optional 避免空值判断
                String region = Optional.ofNullable(customers)
                        .filter(list -> !list.isEmpty())
                        .map(List::getFirst)
                        .map(Customer::get_widget_1722233514707)
                        .orElse(null);
                data.setRegion(region);
                Date widget1733204191654 = customers.getFirst().get_widget_1733204191654();
                Date parsed = DateUtil.parse(date2);
                Date parsed1 = DateUtil.parse(date3);
                long betweenMonths1 = DateUtil.betweenMonth(widget1733204191654, parsed, false);
                long betweenMonths2 = DateUtil.betweenMonth(widget1733204191654, parsed1, false);
                long betweenMonths3 = DateUtil.betweenMonth(widget1733204191654, DateUtil.date(), false);
                data.setFY22_23Growth((int) betweenMonths1);
                data.setFY23_24Growth((int) betweenMonths2);
                data.setFY24_25Growth((int) betweenMonths3);
                data.setFY22_23Grade(ConnmeUtils.getCustomerLevel(customerInfo.getFY23_24SalesAmount()));
                data.setFY22_23Status(data.getFY22_23Growth()>12?"老客户":"新客户");
                data.setFY23_24Status(data.getFY23_24Growth()>12?"老客户":"新客户");
                data.setFY24_25Status(data.getFY24_25Growth()>12?"老客户":"新客户");

                if(result!=null ){
                    if (result.getFYComparison()!=null && result.getFY22_23Jine()!=null){
                        data.setFYComparison(result.getFYComparison());
                        data.setFY22_23Jine(result.getFY22_23Jine());
                    }
                }
                data.setFY23_24Jine(customerInfo.getFY23_24SalesAmount());

                data.setFY23Comparison(percentage);
                data.setDalei(info.getDalei());
                data.setInventoryCode(info.getBianma());
                data.setInventoryName(info.getMingcheng());
                data.setUnit(extractLetters(info.getKuanshi()));
                data.setQuantity(info.getShuliang());
                data.setAmount(info.getFY23_24SalesAmount());
                data.setFinanceYear("FY23-24");

                salesData24.add(data);
            }
            i23++;
            log.info("23年的数据---{}/{}",size23,i23);
        }

        List<CustomerInfo> byxie3 = customerInfoMapper.byxie("2024-07-01", "2024-08-01");
        List<CustomerInfo> byxie31 = customerInfoMapper.sapxie();
        byxie3.addAll(byxie31);
        log.info("即将执行24年的数据");
        int size24 = byxie3.size();
        int i24 = 0;
        BigDecimal totalSalesAmount25 = byxie2.stream()
                .map(CustomerInfo::getFY23_24SalesAmount) // 提取 FY23_24SalesAmount 字段
                .filter(Objects::nonNull) // 过滤掉 null 值，避免空指针异常
                .reduce(BigDecimal.ZERO, BigDecimal::add); // 累加计算总和
        for (CustomerInfo customerInfo : byxie3) {
            BigDecimal percentage = customerInfo.getFY23_24SalesAmount()
                    .divide(totalSalesAmount25, 10, RoundingMode.HALF_UP)
                    .multiply(BigDecimal.valueOf(100));
            List<Customer> customers = getCustomers(customerInfo);

            AtomicReference<SalesData> firstMatchedData24 = new AtomicReference<>();
            AtomicReference<SalesData> firstMatchedData23 = new AtomicReference<>();
            salesData24.stream()
                    .filter(data -> customerInfo.getCustomerCode().equals(data.getTCode()))
                    .peek(data -> {
                        // 只存储第一个匹配的数据到 AtomicReference
                        firstMatchedData24.compareAndSet(null, data);
                    })
                    .forEach(data -> {
                        // 修改所有匹配的数据
                        data.setFY24_25Grade(ConnmeUtils.getCustomerLevel(customerInfo.getFY24_25SalesAmount()));
                        data.setFY23_24Jine(customerInfo.getFY24_25SalesAmount());
                        data.setFY24Comparison(percentage);
                    });
            salesData23.stream()
                    .filter(data -> customerInfo.getCustomerCode().equals(data.getTCode()))
                    .peek(data -> {
                        // 只存储第一个匹配的数据到 AtomicReference
                        firstMatchedData23.compareAndSet(null, data);
                    })
                    .forEach(data -> {
                        // 修改所有匹配的数据
                        data.setFY24_25Grade(ConnmeUtils.getCustomerLevel(customerInfo.getFY24_25SalesAmount()));
                        data.setFY23_24Jine(customerInfo.getFY24_25SalesAmount());
                        data.setFY24Comparison(percentage);
                    });

            SalesData result24 = firstMatchedData24.get();
            SalesData result23 = firstMatchedData23.get();
            List<CustomerInfo> bycode7 = customerInfoMapper.bycode("2024-07-01","2024-08-01",customerInfo.getCustomerCode());
            List<CustomerInfo> bycode8 = customerInfoMapper.sapcode(customerInfo.getCustomerCode());
            bycode7.addAll(bycode8);

            for (CustomerInfo info : bycode7) {
                SalesData data=new SalesData();
                data.setSaleNumber(info.getCode());
                data.setCustomerName(customerInfo.getCustomerName());
                data.setTCode(customerInfo.getCustomerCode());
                data.setSalesDepartment(customerInfo.getFollowUpDepartment());
                data.setBusinessStaff(info.getFollowUpPerson());
                data.setCustomerAttribute(customerInfo.getCustomerAttribute());
                data.setCustomerSource(customerInfo.getCustomerSource());
                // 使用 Optional 避免空值判断
                String region = Optional.ofNullable(customers)
                        .filter(list -> !list.isEmpty())
                        .map(List::getFirst)
                        .map(Customer::get_widget_1722233514707)
                        .orElse(null);
                data.setRegion(region);
                Date widget1733204191654 = customers.getFirst().get_widget_1733204191654();
                Date parsed = DateUtil.parse(date2);
                Date parsed1 = DateUtil.parse(date3);
                long betweenMonths1 = DateUtil.betweenMonth(widget1733204191654, parsed, false);
                long betweenMonths2 = DateUtil.betweenMonth(widget1733204191654, parsed1, false);
                long betweenMonths3 = DateUtil.betweenMonth(widget1733204191654, DateUtil.date(), false);
                data.setFY22_23Growth((int) betweenMonths1);
                data.setFY23_24Growth((int) betweenMonths2);
                data.setFY24_25Growth((int) betweenMonths3);
                data.setFY22_23Grade(ConnmeUtils.getCustomerLevel(customerInfo.getFY23_24SalesAmount()));
                data.setFY22_23Status(data.getFY22_23Growth()>12?"老客户":"新客户");
                data.setFY23_24Status(data.getFY23_24Growth()>12?"老客户":"新客户");
                data.setFY24_25Status(data.getFY24_25Growth()>12?"老客户":"新客户");

                if(result23!=null ){
                    if (result23.getFYComparison()!=null && result23.getFY22_23Jine()!=null){
                        data.setFYComparison(result23.getFYComparison());
                        data.setFY22_23Jine(result23.getFY22_23Jine());
                    }
                }
                if(result24!=null ){
                    if (result24.getFYComparison()!=null && result24.getFY23_24Jine()!=null){
                        data.setFY23Comparison(result24.getFYComparison());
                        data.setFY23_24Jine(result24.getFY23_24Jine());
                    }
                }

                data.setFY24_25Jine(customerInfo.getFY24_25SalesAmount());

                data.setFY24Comparison(percentage);
                data.setDalei(info.getDalei());
                data.setInventoryCode(info.getBianma());
                data.setInventoryName(info.getMingcheng());
                data.setUnit(extractLetters(info.getKuanshi()));
                data.setTCode(customerInfo.getCustomerCode());
                Optional.ofNullable(info.getSapcode()).ifPresent(data::setSAPCode);
                data.setQuantity(info.getShuliang());
                data.setAmount(info.getFY23_24SalesAmount());
                data.setFinanceYear("FY24-25");

                salesData25.add(data);
            }
            i24++;
            log.info("24年的数据---{}/{}",size24,i24);
        }


        log.info("开始写入数据库");
        salesData23.addAll(salesData24);
        salesData23.addAll(salesData25);
        int size = salesData23.size();
        for (int i = 0; i < salesData23.size(); i++) {
            salesDataMapper.insert(salesData23.get(i));
            log.info("{},-------第{}条数据写入成功", size, i);
        }

        return "suu===";
    }

    private static List<Customer> getCustomers(CustomerInfo customerInfo) {
        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> parameterCxv = new HashMap<>();
        parameterCxv.put("app_id", "66a6f42ff97af74b02d217df");
        parameterCxv.put("entry_id", "66a6f443333584e2c128154f");
        HashMap<String, String> communti = new HashMap<>();
        communti.put("_widget_1728356780097 ", customerInfo.getCustomerCode());
        List<Customer> customers = PurchaseCommunity.queryBased(parameterCxv, headers, communti, Customer.class);
        return customers;
    }


    @GetMapping("xiaos")
    public String xiaoshou(){

        List<SalesOrder> fukuandans = new ArrayList<>();
        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", "667230ad22a8581756b77d52");
        parameter.put("entry_id", "667230b322a8581756b78353");

        Map<String, Object> filter = new HashMap<>();
        filter.put("rel", "and");
        Map<String, Object> cond = new HashMap<>();
        cond.put("field", "flowState");
        cond.put("type", "flowstate");
        cond.put("method", "eq");
        List<Integer> values = new ArrayList<>();
        values.add(1);
        cond.put("value", values);
        List<Map<String, Object>> conds = new ArrayList<>();
        conds.add(cond);
        filter.put("cond", conds);
        parameter.put("filter", filter);

        boolean fale = true;
        String zh = "";
        do {
            if (!zh.isEmpty()) {
                parameter.put("data_id", zh);
            }
            parameter.put("limit", 100);
            String jsonSale = JSONUtil.toJsonStr(parameter);
            JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/list", headers, jsonSale);
            String data = jdySale.getStr("data");
            JSONArray objects = JSONUtil.parseArray(data);
            List<SalesOrder> list = JSONUtil.toList(objects, SalesOrder.class);
            if (list.size() == 100) {
                zh = list.getLast().get_id();
            } else {
                fale = false;
            }
            fukuandans.addAll(list);
        } while (fale);

        for (SalesOrder salesOrder : fukuandans) {

                salesOrder.set_widget_1718759603978(null);
                List<String> str = new ArrayList<>();
                str.add("_widget_1718759603990");
                str.add("_widget_1718759603983");
                List<String> str1 = new ArrayList<>();
                str1.add("_widget_1724038210699");
                SalesOrder salesOrder1 = ConnmeUtils.updateFields(salesOrder, str, str1, "_widget_1718759603981");
                Map<String, Object> parameterCxv = new HashMap<>();
                parameterCxv.put("app_id", "667230ad22a8581756b77d52");
                parameterCxv.put("entry_id", "667230b322a8581756b78353");
                HashMap<String, String> communti = new HashMap<>();
                communti.put("_widget_1718759603973", salesOrder1.get_widget_1718759603973());
                List<SalesOrder> salesOrders = PurchaseCommunity.queryBased(parameterCxv, headers, communti, SalesOrder.class);
                salesOrders.sort(Comparator.comparing(SalesOrder::getCreateTime).reversed());


                Map<String, Object> parameterDelete = new HashMap<>();
                parameterDelete.put("instance_id", salesOrder.get_id());
                parameterDelete.put("tasks_type", 1);
                String jsonSale = JSONUtil.toJsonStr(parameterDelete);
                JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/workflow/instance/get", headers, jsonSale);
                JdyPurchaseOrder jdyPurchaseOrder = JSONUtil.toBean(jdySale, JdyPurchaseOrder.class);
                int size = jdyPurchaseOrder.getTasks().size() - 1;
                Task task = jdyPurchaseOrder.getTasks().get(size);

                if (salesOrders.size() == 1) {
                    if (salesOrder1.get_widget_1721814819526() != null) {
                        salesOrder1.set_widget_1718759603988(DateUtil.offsetDay(task.getFinish_time(), salesOrder1.get_widget_1721814819526()));
                    }
                } else {
                    if (salesOrder1.get_widget_1721814819526() == null) {
                        int i = 1;
                        boolean first = true;
                        while (first) {
                            if (salesOrders.get(i).getFlowState() == 1 && salesOrders.get(i).get_widget_1722592892210() != null) {
                                first = false;
                            } else {
                                if (salesOrders.size()-1==i){
                                    first = false;
                                }else {
                                    i++;
                                }

                            }
                        }
                        salesOrder1.set_widget_1718759603988(salesOrders.get(i).get_widget_1718759603988());
                    } else {
                        salesOrder1.set_widget_1718759603988(DateUtil.offsetDay(task.getFinish_time(), salesOrder1.get_widget_1721814819526()));
                    }
                }
                String s = ConnmeUtils.liuChen(salesOrder1.get_id());
                salesOrder1.set_widget_1730973345880(s);
                update(salesOrder1, headers);
            }



        return "xs"+fukuandans.size();
    }



    public String extractLetters(String input) {
        // 防御式编程：检查输入是否为空或为null
        if (input == null || input.trim().isEmpty()) {
            return ""; // 返回空字符串，避免后续处理出错
        }

        // 使用正则表达式提取字母
        return input.replaceAll("[^a-zA-Z]", "");
    }
    private static void update(SalesOrder salesOrder1, Header[] headers) {
        Map<String, Object> parameterInster = new HashMap<>();
        parameterInster.put("app_id", "667230ad22a8581756b77d52");
        parameterInster.put("entry_id", "667230b322a8581756b78353");
        parameterInster.put("is_start_trigger", "true");
        parameterInster.put("data_id", salesOrder1.get_id());
        salesOrder1.set_id(null);
        parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(salesOrder1));
        String jsonSalee = JSONUtil.toJsonStr(parameterInster);
        log.info("销售订单订单更新的数据{}", jsonSalee);
        ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSalee);
    }

    @GetMapping("st")
    public void stockQuantityXxlJob() {
        List<Order0111> order0111s = new ArrayList<>();
        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", "6690c7633df0f4b90b4ef551");
        parameter.put("entry_id", "669df675b02f2a74e35ca2f9");
        boolean fale = true;
        String zh = "";
        do {
            if (!zh.isEmpty()) {
                parameter.put("data_id", zh);
            }
            parameter.put("limit", 100);
            String jsonSale = JSONUtil.toJsonStr(parameter);
            JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/list", headers, jsonSale);
            String data = jdySale.getStr("data");
            JSONArray objects = JSONUtil.parseArray(data);
            List<Order0111> list = JSONUtil.toList(objects, Order0111.class);
            if (list.size() == 100) {
                zh = list.getLast().get_id();
            } else {
                fale = false;
            }
            order0111s.addAll(list);
        } while (fale);

        System.out.println("dererer+++"+order0111s.size());

        for (Order0111 order0111 : order0111s) {
            order0111.set_widget_1721978605698(0);
            order0111.set_widget_1721632911791(0);
            Map<String, Object> parameterCx = new HashMap<>();
            parameterCx.put("app_id", "64a7b7416bbd930007630ed5");
            parameterCx.put("entry_id", "64a7b81afc35ba00082dbcad");
            HashMap<String,String> hashMap=new HashMap<>();
            hashMap.put("purchasing_no", order0111.get_widget_1721628277543());
            hashMap.put("purchasing_hang", order0111.get_widget_1721628277558());
            List<InspectionData> inspectionDataList = PurchaseCommunity.
                    queryBased(parameterCx, headers,hashMap, InspectionData.class);
            if (inspectionDataList == null || inspectionDataList.isEmpty()) {
                // 跳过当前迭代
                continue;
            }
            List<DateTime> dateTimes=new ArrayList<>();
            for (InspectionData inspectionData : inspectionDataList) {
                if (inspectionData.getInspection_result().equals("NG")){
                    continue;
                }
                dateTimes.add(inspectionData.getUpdateTime());
                if (inspectionData.getInspection_place().equals("公司仓库")){
                    order0111.set_widget_1721978605698(inspectionData.getTotal_qty()+ order0111.get_widget_1721978605698());
                    order0111.set_widget_1721632911792(order0111.get_widget_1721978605698());
                } else {
                    order0111.set_widget_1721632911791(inspectionData.getTotal_qty() + order0111.get_widget_1721632911791());
                    order0111.set_widget_1721897497411(order0111.get_widget_1721632911791());
                }
            }
            if (!dateTimes.isEmpty()){
                dateTimes.sort((Comparator.reverseOrder()));
                order0111.set_widget_1736217072169(dateTimes.getFirst());
            }
//            (工厂质检增加数量-广州仓)+(广州仓质检增加数量+工厂仓库存)+(广州仓+工厂仓库存)
            int i = (order0111.get_widget_1721632911791() + order0111.get_widget_1721978605698());
            order0111.set_widget_1721696459065(i);
            if (i>=order0111.get_widget_1721629214715()){
                order0111.set_widget_1721696459066("完成");
            }else {
                order0111.set_widget_1721696459066(null);
            }
            Updatck(headers, order0111);
        }
    }
    private void Updatck(Header[] headers, Order0111 order0111s) {
        Map<String, Object> parameterInster002 = new HashMap<>();
        parameterInster002.put("app_id", "6690c7633df0f4b90b4ef551");
        parameterInster002.put("entry_id", "669df675b02f2a74e35ca2f9");
        parameterInster002.put("is_start_trigger", "true");
        parameterInster002.put("data_id", order0111s.get_id());
        order0111s.set_id(null);
        parameterInster002.put("data", ConnmeUtils.convertEntityToMapNull(order0111s));
        String jsonSale = JSONUtil.toJsonStr(parameterInster002);
        log.info("修改采购改工厂数"+jsonSale);
        JSONObject entries = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSale);
    }


    @Autowired
    private RfmAnalysisMapper rfmAnalysisMapper;

    /**
     * RFM模型
     */
    @GetMapping("/rfm")
    public String rfm(){

        List<RfmAnalysis> rfmAnalyses=new ArrayList<>();
        List<CustomerInfo> xiaohuo = customerInfoMapper.xiaohuo();
        for (CustomerInfo customerInfo : xiaohuo) {
            RfmAnalysis analysis=new RfmAnalysis();
            analysis.setCustomerName(customerInfo.getCustomerName());
            analysis.setCustomerCode(customerInfo.getCustomerCode());
            String dateStr2 = "2024-12-31";
            Date date = DateUtil.parse(dateStr2);
            long l = DateUtil.betweenDay(customerInfo.getLatestSalesDate(), date, false);
            analysis.setR_LastConsumptionMonth(String.valueOf(l));
            Integer count = rfmAnalysisMapper.count(customerInfo.getCustomerCode());
            analysis.setF_ConsumptionFrequency(count);
            analysis.setM_ConsumptionAmount(customerInfo.getFY23_24SalesAmount());
            analysis.setR_Score(defen1((int) l));
            analysis.setF_Score(defen2(count));
            analysis.setM_Score(defen3(customerInfo.getFY23_24SalesAmount()));

            rfmAnalyses.add(analysis);
        }
        int r=0;
        int f=0;
        int m=0;
        int significance = 5; // significance 的值，比如 5
        int sun=rfmAnalyses.size();
        for (RfmAnalysis rf : rfmAnalyses) {
            r+=rf.getR_Score();
            f+=rf.getF_Score();
            m+=rf.getM_Score();
        }
        int c=0;
        for (RfmAnalysis rf : rfmAnalyses) {
            rf.setR_pingjun((float) (r / sun));
            rf.setF_pingjun((float) (f/sun));
            rf.setM_pingjun((float) (m/sun));
            rf.setR_Judgment( ceiling((rf.getR_Score()-rf.getR_pingjun()), significance));
            rf.setF_Judgment( ceiling((rf.getF_Score()-rf.getF_pingjun()), significance));
            rf.setM_Judgment( ceiling((rf.getM_Score()-rf.getM_pingjun()), significance));
            rf.setCustomerCategory(classifyCustomer(rf.getR_Judgment(),rf.getF_Judgment(),rf.getM_Judgment()));
            rfmAnalysisMapper.insert(rf);
            log.info("正在处理数据，总数{},现在是第{}",sun,c++);
        }

        return "rfm";
    }

    public static String classifyCustomer(Float R, Float F, Float M) {
        if (isEqual(R, 0.0f) && isEqual(F, 5.0f) && isEqual(M, 5.0f)) {
            return "VIP客户";
        } else if (isEqual(R, 0.0f) && isEqual(F, 5.0f) && isEqual(M, 0.0f)) {
            return "重要发展客户";
        } else if (isEqual(R, 0.0f) && isEqual(F, 0.0f) && isEqual(M, 5.0f)) {
            return "重要保持客户";
        } else if (isEqual(R, 0.0f) && isEqual(F, 0.0f) && isEqual(M, 0.0f)) {
            return "留存客户";
        } else if (isEqual(R, 5.0f) && isEqual(F, 5.0f) && isEqual(M, 5.0f)) {
            return "唤醒客户";
        } else if (isEqual(R, 5.0f) && isEqual(F, 5.0f) && isEqual(M, 0.0f)) {
            return "潜在培养客户";
        } else if (isEqual(R, 5.0f) && isEqual(F, 0.0f) && isEqual(M, 5.0f)) {
            return "重要挽留客户";
        } else if (isEqual(R, 5.0f) && isEqual(F, 0.0f) && isEqual(M, 0.0f)) {
            return "一般客户";
        } else {
            return "未知分类";
        }
    }

    // Helper method to compare Float values considering precision issues
    private static boolean isEqual(Float a, Float b) {
        final float EPSILON = 0.0001f; // Define a small precision threshold
        return Math.abs(a - b) < EPSILON;
    }
    public static float ceiling(double value, int significance) {
        if (significance == 0) {
            throw new IllegalArgumentException("Significance cannot be 0.");
        }
        return (float) (Math.ceil(value / significance) * significance);
    }

    private Float defen1(Integer tian){
        if (tian>180){
            return 5.0f;
        }else if (tian>90){
            return 4.0f;
        }else if (tian>=60){
            return 3.0f;
        }else if (tian>=20){
            return 2.0f;
        }else {
            return 1.0f;
        }
    }
    private Float defen2(Integer pinglu){

        if (pinglu>=7){
            return 5.0f;
        }else if (pinglu>=5){
            return 4.0f;
        }else if (pinglu>=3){
            return 3.0f;
        }else if (pinglu>=2){
            return 2.0f;
        }else {
            return 1.0f;
        }
    }
    private Float defen3(BigDecimal jine) {
        if (jine.compareTo(new BigDecimal("5000000")) >= 0) {
            return 5.0f;
        } else if (jine.compareTo(new BigDecimal("100000")) >= 0) {
            return 4.0f;
        } else if (jine.compareTo(new BigDecimal("50000")) >= 0) {
            return 3.0f;
        } else if (jine.compareTo(new BigDecimal("10000")) >= 0) {
            return 2.0f;
        } else {
            return 1.0f;
        }
    }

    @Autowired
    private ConsolidatedOrdersMapper consolidatedOrdersMapper;

    @Transactional
    @GetMapping("xsdd")
    public String xxdd(){
        List<ConsolidatedOrders> chaxun = consolidatedOrdersMapper.chaxun();
        int i =0;
        for (ConsolidatedOrders consolidatedOrders : chaxun) {
            BigDecimal fy2324dde = consolidatedOrders.getFy23_24dde();
            if (fy2324dde!=null){
                if (fy2324dde.compareTo(new BigDecimal("10000000")) >= 0) {
                    consolidatedOrders.setKhdji23("GSKA");
                } else if (fy2324dde.compareTo(new BigDecimal("3000000")) >= 0) {
                    consolidatedOrders.setKhdji23("SKA");
                } else if (fy2324dde.compareTo(new BigDecimal("1000000")) >= 0) {
                    consolidatedOrders.setKhdji23("KA");
                } else if (fy2324dde.compareTo(new BigDecimal("300000")) >= 0) {
                    consolidatedOrders.setKhdji23("PA");
                } else {
                    consolidatedOrders.setKhdji23("AA");
                }
            }
            BigDecimal fy2425dde = consolidatedOrders.getFy24_25dde();
            if (fy2425dde!=null){
                if (fy2425dde.compareTo(new BigDecimal("10000000")) >= 0) {
                    consolidatedOrders.setKhdji24("GSKA");
                } else if (fy2425dde.compareTo(new BigDecimal("3000000")) >= 0) {
                    consolidatedOrders.setKhdji24("SKA");
                } else if (fy2425dde.compareTo(new BigDecimal("1000000")) >= 0) {
                    consolidatedOrders.setKhdji24("KA");
                } else if (fy2425dde.compareTo(new BigDecimal("300000")) >= 0) {
                    consolidatedOrders.setKhdji24("PA");
                } else {
                    consolidatedOrders.setKhdji24("AA");
                }
            }

            if (consolidatedOrders.getId()==null){
                System.out.println();
            }
            consolidatedOrdersMapper.insert(consolidatedOrders);
            log.info("现在执行总数{}/{}",chaxun.size(),i++);
        }
        return "sss";
    }


    @GetMapping("xinbaoCreate")
    public String xinbaoCreate() {
        Header[] headers = ConnmeUtils.createHeaders();
        Header[] headers1 = new Header[3];
        String auth = KeyConstant.sapName + ":" + KeyConstant.sapPass;
        String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes());
        String authHeader = "Basic " + encodedAuth;
        headers1[0] = new BasicHeader("Accept", "application/json");
        headers1[1] = new BasicHeader("Authorization", authHeader);
        headers1[2] = new BasicHeader("x-csrf-token", "Fetch");
        JSONObject entries1 =
                ApiClient.sendGetRequest("https://my200654-api.s4hana.sapcloud.cn/sap/opu/odata/sap/API_OUTBOUND_DELIVERY_SRV;v=0002/A_OutbDeliveryHeader", headers1, null);
        String d1 = entries1.getStr("d");
        JSONObject objects1 = JSONUtil.parseObj(d1);
        String results1 = objects1.getStr("results");
        JSONArray objectss1 = JSONUtil.parseArray(results1);
        List<WaiXiangJIaohuoVO> waiXiangJIaohuoVOList = JSONUtil.toList(objectss1, WaiXiangJIaohuoVO.class).stream()
                .filter(Objects::nonNull) // 过滤掉可能存在的 null 元素
                .collect(Collectors.collectingAndThen(
                        // 使用 TreeSet 保证元素的唯一性，根据字段 a 进行比较
                        Collectors.toCollection(() -> new java.util.TreeSet<>(Comparator.comparing(WaiXiangJIaohuoVO::getDeliveryDocument))),
                        ArrayList::new // 将 TreeSet 转换为 ArrayList
                ));

        Iterator<WaiXiangJIaohuoVO> iterator = waiXiangJIaohuoVOList.iterator();
        DateTime now = DateTime.now(); // 获取当前时间，只调用一次提高效率

        while (iterator.hasNext()) {
            WaiXiangJIaohuoVO waiXiangJIaohuoVO = iterator.next();

            // 检查字段是否不为空
            if (waiXiangJIaohuoVO.getYY1_YY1_lachangedateti_DLH() != null
                    && !waiXiangJIaohuoVO.getYY1_YY1_lachangedateti_DLH().isBlank()) {

                // 提取并转换时间戳
                long lct = Long.parseLong(ConnmeUtils.extractTimestamp(waiXiangJIaohuoVO.getYY1_YY1_lachangedateti_DLH()));
                LocalDateTime dateTime2 = ConnmeUtils.convertTimestampToLocalDateTime(lct);
                String formattedDateTime2 = ConnmeUtils.formatDateTime(dateTime2);
                DateTime dateTime4 = new DateTime(formattedDateTime2, DatePattern.NORM_DATETIME_FORMAT);

                // 设置解析后的时间对象回到 VO
                waiXiangJIaohuoVO.setYY1_YY1_lachangedateti_DLHs(dateTime4);

                // 判断日期是否是今天
                if (!DateUtil.isSameDay(dateTime4, now) || !"true".equals(waiXiangJIaohuoVO.getYY1_IF_Release_WMS_DLH())) {
                    iterator.remove();
                } else {
                    //交货单_明细调用表
                    Map<String, Object> cgdd = new HashMap<>();
                    cgdd.put("app_id", "668f82dc2f5940fc022143d3");
                    cgdd.put("entry_id", "6748024897dca2bc77466848");
                    HashMap<String, String> communti = new HashMap<>();
                    communti.put("_widget_1730770509313", waiXiangJIaohuoVO.getDeliveryDocument());
                    List<WaiXiangJIaohuoVO> waiXiangJIaohuoVOS = PurchaseCommunity.queryBased(cgdd, headers, communti, WaiXiangJIaohuoVO.class);
                    if (waiXiangJIaohuoVOS.isEmpty()) {
                        continue;
                    }
                    //客户编码
                    String widget1732772568399 = waiXiangJIaohuoVOS.getFirst().get_widget_1732772568399();
                    //客户主数据
                    Map<String, Object> kehu = new HashMap<>();
                    kehu.put("app_id", "66a6f42ff97af74b02d217df");
                    kehu.put("entry_id", "66a6f443333584e2c128154f");
                    HashMap<String, String> kehuc = new HashMap<>();
                    kehuc.put("_widget_1722305048887", widget1732772568399);
                    List<Customer> customers = PurchaseCommunity.queryBased(kehu, headers, kehuc, Customer.class);
                    if (customers.isEmpty()) {
                        continue;
                    }
                    String widget1732245038716 = customers.getFirst().get_widget_1732245038716();
                    if (!widget1732245038716.equals("是")) {
                        continue;
                    }

                    Map<String, Object> waixiang = new HashMap<>();
                    waixiang.put("app_id", "668f82dc2f5940fc022143d3");
                    waixiang.put("entry_id", "6752b495ab2359bc29a39a50");
                    HashMap<String, String> jiaohuo = new HashMap<>();
                    jiaohuo.put("_widget_1733473428479", waiXiangJIaohuoVO.getDeliveryDocument());
                    List<DeliveryInfo> deliveryInfos = PurchaseCommunity.queryBased(waixiang, headers, jiaohuo, DeliveryInfo.class);
                    if (deliveryInfos.isEmpty()) {
                        DeliveryInfo deliveryInfo = new DeliveryInfo();
                        deliveryInfo.set_widget_1733473428480(customers.getFirst().get_widget_1722217596682());
                        deliveryInfo.set_widget_1733473428479(waiXiangJIaohuoVO.getDeliveryDocument());
                        deliveryInfo.set_widget_1740636897665(waiXiangJIaohuoVOS.getFirst().get_widget_1732764831222().get("username"));
                        deliveryInfo.set_widget_1733473796643(waiXiangJIaohuoVO.getSalesOrganization());

                        Map<String, Object> parameterInster = new HashMap<>();
                        parameterInster.put("app_id", "668f82dc2f5940fc022143d3");
                        parameterInster.put("entry_id", "6752b495ab2359bc29a39a50");
                        parameterInster.put("is_start_trigger", "true");
                        deliveryInfo.set_id(null);
                        parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(deliveryInfo));
                        String jsonSale = JSONUtil.toJsonStr(parameterInster);
                        log.info("外向交货单_是否允许交货--{}", jsonSale);
                        ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/create", headers, jsonSale);
                    }

                }


            } else {
                iterator.remove(); // 如果字段为空或 null，也移除
            }
        }


        log.info(String.valueOf(waiXiangJIaohuoVOList.size()));
        return "suu===" + waiXiangJIaohuoVOList.size();
    }

}
